<?php
namespace Common\Model;

use Common\Common\GlobalParam;
use Think\Log;
use Think\Model\RelationModel;

class CrmCustomModel extends RelationModel
{
    protected $_validate = array(
        array('name', 'require', '名称不能为空', self::EXISTS_VALIDATE, 'regex', self::MODEL_BOTH),
//        array('tel', '\d{3}-\d{8}|\d{4}-\d{7}', '电话号码错误', self::EXISTS_VALIDATE, 'regex', self::MODEL_BOTH),
    );

    protected $_auto = array(
        array('create_time', NOW_TIME, self::MODEL_INSERT),
        array('state', '0', self::MODEL_BOTH),
    );
    protected $_link = array(
        'custom_contacts' => array(
            'mapping_type' => self::HAS_MANY,
            'class_name' => 'CrmCustomContact',
            'foreign_key' => 'custom_id',
            'condition' => 'state>=0',
        ),
        'custom_activities' => array(
            'mapping_type' => self::HAS_MANY,
            'class_name' => 'CrmActivity',
            'foreign_key' => 'custom_id',
            'condition' => 'state>=0',
            'mapping_order' => 'activity_time desc',
        ),
    );

    public function update($data)
    {
        if (empty($data['id'])) {
            $result = $this->add($data);
            fc_set_temp_statistics($data['add_user_id'], 'add_count', 1);
        } else {
            $result = $this->save($data);
        }
        return $result;
    }

    public function delete($id, $add_user_id)
    {
        $data['state'] = -1;
        $result = $this->where('id=%d', $id)->save($data);
        fc_set_temp_statistics($add_user_id, 'add_count', -1);
        if ($result) {
            return true;
        }
        return false;
    }

    public function get($id)
    {
        $condition = array();
        $condition['id'] = array('eq', $id);
        $condition['state'] = array('egt', 0);
        $model = $this->relation(true)->field(true)->where($condition)->find();
        return $model;
    }

    public function allot($ids, $target_user_id, $operate_user)
    {
//        if ($target_user_id == $operate_user['id']) {
//            return true;
//        }
        $this->startTrans();
        $condition = array();
        $allocationModel = D('CrmCustomAllocation');
        $result = [];
        foreach ($ids as $id) {
            if (!empty($id)) {
                $condition['id'] = array('eq', $id);

                $model = $this->relation(false)->where($condition)->find();
                $source_user_id = $model['leader_user_id'];
                $model['state'] = 1;
                $model['leader_user_id'] = $target_user_id;
                $r = $this->save($model);

                $log = $allocationModel->create();
                $log['custom_id'] = $model['id'];
                $log['target_user_id'] = $model['leader_user_id'];
                $log['operate_user_id'] = $operate_user['id'];
                $log['type'] = 0;
                $log['create_time'] = NOW_TIME;
                $row = $allocationModel->add($log);

                if (!empty($source_user_id)) {
                    fc_set_temp_statistics($source_user_id, 'follow_count', -1, false);
                }
                fc_set_temp_statistics($target_user_id, 'follow_count', 1);
                $result[] = $r && $row;
            }
        }

        foreach ($result as $value) {
            if (!$value) {
                $this->rollback();
                return false;
            }
        }

        $this->commit();
        return true;
    }

    public function back($id, $operate_user)
    {
        $this->startTrans();
        $condition = array();
        $condition['id'] = array('eq', $id);
        $condition['state'] = array('egt', 0);
        if ($operate_user['role'] <= 1) {
            $condition['leader_user_id'] = $operate_user['id'];
        }
        $model = $this->relation(false)->where($condition)->find();
        $leader_user_id = $model['leader_user_id'];

//        $manager = fc_get_manager($leader_user_id);

        $model['state'] = 0;
//        if ($manager != null && $manager['id'] != $operate_user['id']) {
//            $model['leader_user_id'] = $manager['id'];
//        } else {
//            $model['leader_user_id'] = null;
//        }
        $model['leader_user_id'] = null;
        $result = $this->save($model);

        $allocationModel = D('CrmCustomAllocation');

        $log = $allocationModel->create();

        $log['custom_id'] = $model['id'];
        $log['target_user_id'] = $model['leader_user_id'];
        $log['operate_user_id'] = $operate_user['id'];
        $log['type'] = 1;
        $log['create_time'] = NOW_TIME;

        $row = $allocationModel->add($log);

        if ($result && $row) {
            fc_set_temp_statistics($operate_user['id'], 'follow_count', -1, false);
            $this->commit();
            return true;
        } else {
            $this->rollback();
        }
        return false;
    }

    public function sign($id, $operate_user)
    {
        $condition = array();
        $condition['id'] = array('eq', $id);
        $condition['state'] = array('egt', 0);

        $model = $this->relation(false)->where($condition)->find();
        $model['state'] = 2;
        $model['sign_user_id'] = $operate_user['id'];
        $model['sign_time'] = NOW_TIME;

        $result = $this->save($model);
        fc_set_temp_statistics($operate_user['id'], 'signed_count', 1);
        return $result;
    }

    public function get_list($leader_user_id, $search_key, $search_type, $search_distribute, $page_no = 1, $page_size = 0)
    {
        $condition = $this->assembleCondition($leader_user_id, $search_key, $search_type, $search_distribute);

        $count = 0;
        $list = [];
        if ($page_size > 0) {
            $list = $this->where($condition)->order('id desc')->limit(($page_no - 1) * $page_size, $page_size)->select();
            $count = $this->where($condition)->count();
        } else {
            $list = $this->where($condition)->order('id desc')->select();
        }
        return [$list, $count];
    }

    public function get_sea_list($leader_user_id, $search_key, $search_type, $search_distribute, $page_no = 1, $page_size = 0)
    {
        $condition = $this->assembleCondition($leader_user_id, $search_key, $search_type, $search_distribute);
        $condition['leader_user_id'] = array('EXP', 'IS NULL');;

        $count = $this->where($condition)->count();
        if ($page_size > 0) {
            $list = $this->where($condition)->limit(($page_no - 1) * $page_size, $page_size)->select();
        } else {
            $list = $this->where($condition)->select();
        }

        return [$list, $count];
    }

    public function get_singed_list($leader_user_id, $sign_user_id, $search_key, $search_type, $search_distribute, $page_no = 1, $page_size = 0)
    {
        $condition = $this->assembleCondition($leader_user_id, $search_key, $search_type, $search_distribute);
        $condition['sign_user_id'] = $sign_user_id;

        $count = $this->where($condition)->count();
        if ($page_size > 0) {
            $list = $this->where($condition)->limit(($page_no - 1) * $page_size, $page_size)->select();
        } else {
            $list = $this->where($condition)->select();
        }

        return [$list, $count];
    }

    private function assembleCondition($leader_user_id, $search_key, $search_type, $state)
    {
        $condition = array();
        if (!empty($leader_user_id)) {
            if (is_array($leader_user_id)) {
                $condition['leader_user_id'] = array('in', $leader_user_id);
            } else {
                $condition['leader_user_id'] = array('eq', $leader_user_id);
            }
        }
        if (!empty($search_key)) {
            $condition['name'] = array('like', '%' . $search_key . '%');
        }
        if (!empty($search_type)) {
            $condition['type'] = array('eq', $search_type);
        }

        if ($state != "" && $state != null) {
            $condition['state'] = array('eq', $state);
        } else {
            $condition['state'] = array('between', array(GlobalParam::$Custom_State_Undistributed, GlobalParam::$Custom_State_Distributed));
        }

        return $condition;
    }
}